import { defineStore } from 'pinia'
import Cookies from 'js-cookie'
import { Session, Local } from '@/utils/storage'
import { ElMessage } from 'element-plus'
import { doLogin, doLogout, getCaptcha } from '@/api/auth'
import type { LoginForm, LoginVO, CaptchaResult } from '@/api/auth/types'
const TOKEN_KEY = ''

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserStore = defineStore('userStore', {
    state: (): UserInfoState => ({
        userInfo: {
            userName: '',
            photo: '',
            time: 0,
            roles: [],
            authBtnList: [],
        },
    }),
    actions: {
        /**
         * 登录
         * @param userInfo
         * @returns
         */
        login(loginForm: LoginForm) {
            return new Promise<void>((resolve, reject) => {
                const isNoPower = false
                if (isNoPower) {
                    ElMessage.warning('抱歉，您没有登录权限')
                    Session.clear()
                    reject()
                } else {
                    Session.set('token', Math.random().toString(36).substr(0))
                }

                resolve()
                // doLogin(loginForm)
                //     .then((resp: LoginVO) => {
                //         const { access_token } = resp
                //         Local.set(TOKEN_KEY, access_token)
                //         resolve()
                //     })
                //     .catch((err) => {
                //         reject(err)
                //     })
            })
        },
        /**
         * 获取用户信息
         */
        getUserInfo() {},

        /**
         * 退出登录
         */
        logout() {
            return new Promise<void>((resolve, reject) => {
                doLogout()
                    .then(() => {
                        Local.remove(TOKEN_KEY)
                        location.reload() // 清空路由
                        resolve()
                    })
                    .catch((e) => {
                        reject(e)
                    })
            })
        },

        async setUserInfo() {
            // 存储用户信息到浏览器缓存
            if (Session.get('userInfo')) {
                this.userInfo = Session.get('userInfo')
            } else {
                const userInfo: any = await this.getApiUserInfo()
                this.userInfo = userInfo
            }
        },
        // 模拟接口数据
        // https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
        async getApiUserInfo() {
            return new Promise((resolve) => {
                setTimeout(() => {
                    // 模拟数据，请求接口时，记得删除多余代码及对应依赖的引入
                    const userName = Cookies.get('userName')
                    // 模拟数据
                    let defaultRoles: Array<string> = []
                    let defaultAuthBtnList: Array<string> = []
                    // admin 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
                    const adminRoles: Array<string> = ['admin']
                    // admin 按钮权限标识
                    const adminAuthBtnList: Array<string> = [
                        'btn.add',
                        'btn.del',
                        'btn.edit',
                        'btn.link',
                    ]
                    // test 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
                    const testRoles: Array<string> = ['common']
                    // test 按钮权限标识
                    const testAuthBtnList: Array<string> = [
                        'btn.add',
                        'btn.link',
                    ]
                    // 不同用户模拟不同的用户权限
                    if (userName === 'admin') {
                        defaultRoles = adminRoles
                        defaultAuthBtnList = adminAuthBtnList
                    } else {
                        defaultRoles = testRoles
                        defaultAuthBtnList = testAuthBtnList
                    }
                    // 用户信息模拟数据
                    const userInfos = {
                        userName: userName,
                        photo:
                            userName === 'admin'
                                ? 'http://p7.itc.cn/q_70/images03/20201227/03835f168e884607b678310f53278514.jpeg?w=504&h=500'
                                : 'http://p7.itc.cn/q_70/images03/20201227/03835f168e884607b678310f53278514.jpeg?w=500&h=500',
                        time: new Date().getTime(),
                        roles: defaultRoles,
                        authBtnList: defaultAuthBtnList,
                    }
                    Session.set('userInfo', userInfos)
                    resolve(userInfos)
                }, 0)
            })
        },
    },
})
